package com.text.controller;

import com.github.pagehelper.PageInfo;
import com.text.entity.Users;
import com.text.service.UsersService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;


/**
 * (Users)表控制层
 *
 * @author makejava
 * @since 2023-06-02 15:08:19
 */
@RestController
@RequestMapping("/admin")
public class UsersController {
    /**
     * 服务对象
     */
    @Resource
    private UsersService usersService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     *
     * @param users 筛选条件
     * @return 查询结果
     */
    @GetMapping("/usersList")
    public ResponseEntity<PageInfo<Users>> queryByPage(@RequestBody(required = false) Users users,
                                                       @RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
                                                       @RequestParam(value = "pageSize",required = false,defaultValue = "5") Integer pageSize) {
        PageInfo<Users> usersListPage = this.usersService.queryByPage(users,pageNum,pageSize);
        return ResponseEntity.ok(usersListPage);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/user/{id}")
    public ResponseEntity<Users> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.usersService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param users 实体
     * @return 新增结果
     */
    @PostMapping("/usersAdd")
    public ResponseEntity<Users> add(@RequestBody Users users) {
        return ResponseEntity.ok(this.usersService.insert(users));
    }

    /**
     * 编辑数据
     *
     * @param users 实体
     * @return 编辑结果
     */
    @PutMapping("/usersEdit")
    public ResponseEntity<Users> edit(@RequestBody Users users) {
        Users u = this.usersService.update(users);
        redisTemplate.opsForValue().set("user_" + users.getId(),u);
        return ResponseEntity.ok(u);
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("/userDelete")
    public ResponseEntity<Boolean> deleteById(Integer id) {
        boolean f =this.usersService.deleteById(id);
        redisTemplate.delete("user_" + id);
        return ResponseEntity.ok(f);
    }

}

